Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Return True if n is a happy number, and False if not.
快樂數(Happy Number)定義是,整數中的每個位數平方後相加,其結果再做同樣的操作,直到結果為1
,就是快樂數,若一直循環不是1
的話,就不是快樂數。
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
設定邊界條件,若小於1
,不成立。
若,不等於1
,且沒有重複的話就繼續計算,直到結果為1
,n
為參數,將n
的各位數拆分為陣列s
,計算每個位數的平方和:
n = s.map(e => e * e).reduce((acc, cur) => acc + cur);
var isHappy = function(n) {
let array = [];
if (n < 1) {
return false;
}
while (n !== 1) {
let s = ('' + n).split('');
n = s.map(e => e * e).reduce((acc, cur) => acc + cur);
if (array.includes(n)) {
return false
}
array.push(n);
}
return true;
};